package k8s

import (
	"fmt"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"reflect"
)

type K8sJob struct {
	Name string						`json:"name"`
	Namespace string				`json:"namespace"`
	Labels map[string]string		`json:"labels"`
	ContainerGroup string			`json:"containergroup"`
	Images []string					`json:"images"`
	RunStatus string				`json:"runStatus"`


	CreateDate string				`json:"createdate"`
	Pods []K8sPod 					`json:"pods"`
	Events []Event					`json:"events"`
}


func GetJobDetail(ns string,name string)(k8sJob K8sJob,err error) {
	job, _ := clientset.BatchV1().Jobs(ns).Get(name,metav1.GetOptions{})

	fmt.Println(reflect.TypeOf(job))

	k8sJob = K8sJob{
		Name: job.Name,
		Namespace: job.Namespace,
		Labels: job.Labels,
		Images: func() []string{
			var images []string
			for _,i := range job.Spec.Template.Spec.Containers {
				images = append(images,i.Image)
			}
			return images
		}(),
		CreateDate: job.CreationTimestamp.Format("2006-01-02 15:04:05"),
		RunStatus: fmt.Sprintf("%d 活跃中,%d 已成功,%d 已失败",job.Status.Active,job.Status.Succeeded,job.Status.Failed),
		Events: getEventsForJob(job),
	}


	Selector , _ := metav1.LabelSelectorAsSelector(job.Spec.Selector)

	fmt.Printf("%+v\n",job.Spec.Selector)

	pods,_ := clientset.CoreV1().Pods(ns).List(metav1.ListOptions{
		LabelSelector: Selector.String(),
	})

	for _,pod := range pods.Items {

		var status string
		if pod.Status.ContainerStatuses[0].State.Terminated != nil {
			status = "Terminated " + pod.Status.ContainerStatuses[0].State.Terminated.Reason
		} else if pod.Status.ContainerStatuses[0].State.Running != nil {
			status = "Running"
		} else if pod.Status.ContainerStatuses[0].State.Waiting != nil {
			status = "Waiting " + pod.Status.ContainerStatuses[0].State.Waiting.Reason
		} else {
			status = "Unknown State ! "
		}

		k8sJob.Pods = append(k8sJob.Pods, K8sPod{
			Name:         pod.Name,
			Status:       status,
			//NodeIp:       string(n),
			NodeName: pod.Spec.NodeName,
			PodIp:        pod.Status.PodIP,
			RestartCount: pod.Status.ContainerStatuses[0].RestartCount,
			CreateDate:   pod.CreationTimestamp.Format("2006-01-02 15:04:05"),
		})
	}


	return
}

func getJobs(name string)(k8sJobs []K8sJob, err error)  {
	jobs,_ := clientset.BatchV1().Jobs(name).List(metav1.ListOptions{})
	//fmt.Printf("%+v\n",dp)
	for _,job := range jobs.Items {
		k8sJobs = append(k8sJobs,K8sJob{
			Name: job.Name,
			Labels: job.Labels,
			ContainerGroup: fmt.Sprintf("%d / %d",job.Status.Active,*job.Spec.Completions),
			CreateDate: job.CreationTimestamp.Format("2006-01-02"),
			Images: func() []string{
				var images []string
				for _,i := range job.Spec.Template.Spec.Containers {
					images = append(images,i.Image)
				}
				return images
			}(),
		})
	}

	return
}